package com.calculator;

import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 8/21/13
 * Time: 1:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class StringCalculatorApp {

    private String delimiter = ",|\\n";
    private int result = 0;
    private boolean negatives = false;
    private String negativesInLine = "";
    private String numbersSplit[];

    public static void main(String[] args) {

        try {
            System.out.println(new StringCalculatorApp().add("//[$]\n1$-1000$2$2$1000$3$-999"));
        } catch (NegativeException e) {
            System.out.println(e.getMessage());
        }
    }


    public Integer add(String numbers) throws NegativeException {

        if(numbers.isEmpty()) return 0;

        String numbersWithoutDelimiter = findDelimiter(numbers);

        numbersSplit = numbersWithoutDelimiter.split(delimiter);

        calculateSumOfNumbers(numbersSplit);

        checkForNegativeFlag();

        return result;
    }

    private String findDelimiter(String numbers) {
        if (!getDelimiter(numbers).isEmpty()){
            delimiter = Pattern.quote(getDelimiter(numbers));
            numbers = getAfterDelimiter(numbers);
        }
        return numbers;
    }

    public String getDelimiter(String numbers) {
        String delimiter = "";
        if(numbers.indexOf("//[") == 0){
            delimiter = numbers.substring(3, numbers.indexOf("]\n") ) ;
        }
        return delimiter;
    }


    public String getAfterDelimiter(String numbersWithDelimiter) {
        String numbersOnly = numbersWithDelimiter;
        int positionEnd = numbersWithDelimiter.indexOf("]\n");
        if(positionEnd != -1){
            numbersOnly = numbersWithDelimiter.substring(numbersWithDelimiter.indexOf("]\n") + 2, numbersWithDelimiter.length() );
        }
        return numbersOnly;
    }

    private void calculateSumOfNumbers(String[] numbers) {
        if (numbers.length != 0){
            for (String number : numbers) {
                int numberParsed = Integer.parseInt(number);
                if (numberParsed < 0){
                    negatives = true;
                    negativesInLine += (number + ",");
                }
                if(numberParsed <= 1000){
                    result += numberParsed  ;
                }
            }
        }
    }

    private void checkForNegativeFlag() throws NegativeException {
        if(negatives){
            throw new NegativeException("Negatives not allowed:" + negativesInLine.substring(0, negativesInLine.length() - 1));
        }
    }
}
